package com.example.yan_music.model.net;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import com.example.yan_music.app.Api;
import com.example.yan_music.app.XApplication;
import com.example.yan_music.utils.XDataPool;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.Retrofit.Builder;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *  封装 Retrofit
 */
public class RetrofitFactory {
    private static Retrofit mRetrofit;
    private static Retrofit mSongPlayUrlRetrofit; // 播放歌曲的请求retrofit
    private static OkHttpClient mOkClient;

    // 创建网络请求的 Observable
    public static NetRetrofitService createRequest(){
        return RetrofitFactory.getRetrofit().create(NetRetrofitService.class);
    }

    // 获取Retrofit
    private synchronized static Retrofit getRetrofit(){
        if(mRetrofit == null){
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(Api.LOCAL_HOST)
                    .client(getOkHttpClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return mRetrofit;
    }

    /**
     * 获取 OkHttp client
     *
     * @return  OkHttpClient
     */
    private synchronized static OkHttpClient getOkHttpClient() {
        // 日志类
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志, 打印出请求完整的地址
                Log.d("RetrofitLog","retrofitBack = "+message);
            }
        });

        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        if (mOkClient == null) {
            mOkClient = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .connectTimeout(100, TimeUnit.SECONDS)  // TimeUnit.SECONDS线程等待100秒
                    .build();
        }
        return mOkClient;
    }


}
